class EventBus{
  constructor(){
    this.listeners = {}
  } 
  // 订阅事件 on/subscribe
  on(type, callback){
    let events = this.listeners[type] || [];
    events.push(callback);
    this.listeners[type] = events;
  }
  // 解绑事件 off/unsubscribe
  off(type, callback){
    let events = this.listeners[type] || [];
    let index = events.findIndex(event => event === callback);
    if (index !== -1){
      this.listeners[type].splice(index, 1);
    }
  }
  // 只绑定一次
  once(type, callback){
    const wrapCallback = ()=>{
      callback();
      this.off(type, wrapCallback); 
    }
    this.on(type, wrapCallback);
  }
}

function subscribe(listener) {
  if (typeof listener !== 'function') {
    throw new Error('Expected listener to be a function.')
  }

  let isSubscribed = true

  ensureCanMutateNextListeners()
  nextListeners.push(listener)
}

function unsubscribe(listener) {
  ensureCanMutateNextListeners()
  const index = nextListeners.indexOf(listener)
  index !== -1? nextListeners.splice(index, 1): null;
}